<?php

/**
 * @Author: Mr.Mao
 * @Date:   2021-08-02 13:45:16
 * @Last Modified by:   Mr.Mao
 * @Last Modified time: 2021-11-18 14:09:52
 */
namespace app\publics\controller\api;
use app\ApiController;
use app\shop\model\OrderModel;
use app\member\model\UsersModel;
use app\distribution\model\DividendAwardModel;
use app\distribution\model\DividendModel;
use app\member\model\AccountModel;
use think\Db;
use think\facade\Cache;
/*------------------------------------------------------ */
//-- 文章
/*------------------------------------------------------ */
class Timer extends ApiController
{
	/*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new DividendModel();
        $this->AccountModel = new AccountModel();
    }
    /**
     * [每日冻积分释放]
     * @return [type] [description]
     */
    public function integralSend()
    {
        //今日营业额
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $totalMoney = db("shop_order_info")->where("pay_status=1 and pay_time>=$beginToday")->sum("order_amount");
        if(!$totalMoney){
            $totalMoney = 0;
        }
        $DividendInfo = settings('DividendInfo');
        $award = $totalMoney*($DividendInfo['sf_integral_rebate']/100);
        //总的冻积分
        $where = [];
        $where[] = ['use_integral', '>', 0 ];
        $totalAccount = db("users_account")->where($where)->sum("use_integral");
        if(!$totalAccount){
            $totalAccount = 0;
        }
        if($totalAccount>0 && $award>0 && $account = db("users_account")->where($where)->group("user_id")->select()){
            foreach ($account as $k=>$v){
                $per_bl = round($v['use_integral']/$totalAccount, 3);
                $per_award = $award*$per_bl;
                if($v['use_integral']<$per_award){
                    $per_award = $v['use_integral'];
                }
                if($per_award>0){
                    $data = [];
                    $data['change_desc'] = $per_award."冻积分释放入余额";
                    $data['change_type'] = 11;
                    $data['by_id'] = 0;
                    $data['use_integral'] = $per_award*-1;
                    $res = $this->AccountModel->change($data, $v['user_id'], false);
                    $data1 = [];
                    $data1['change_desc'] = $per_award."冻积分释放入余额";
                    $data1['change_type'] = 11;
                    $data1['by_id'] = 0;
                    $data1['balance_money'] = $per_award;
                    $res = $this->AccountModel->change($data1, $v['user_id'], false);
                }
            }
        }
        echo "success";exit();
    }
    /**
     * [day 日分红]
     * @return [type] [description]
     */
    public function day()
    {
        set_time_limit(0);

        // $get_ip = request()->ip();
        // if ($get_ip != '106.52.20.114') {
        //     die('【IP无权访问】');
        // }
        // $isBouns = Cache::get('dayBouns_' . date('Ymd'));
        // if ($isBouns == true) {
        //     die('【今日已分红】');
        // }
        // Cache::set('dayBouns_' . date('Ymd'), true, 86400);

        $start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $end = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;

        $OrderModel = new OrderModel();
        $where = [];
        $where[] = ['order_status', '=', 1];
        $where[] = ['order_type', '=', 4];
        $where[] = ['add_time', 'between', [$start, $end]];
        $orderTotal = $OrderModel
        ->where($where)
        ->field('sum(order_amount) as total_amount , sum(shipping_fee) total_fee , sum(discount) as total_discount , sum(diy_discount) as total_diy_discount')
        ->find()
        ->toArray();
        $total = $orderTotal['total_amount'] - $orderTotal['total_fee'] - $orderTotal['total_discount'] - $orderTotal['total_diy_discount'];
        $userLevel = (new \app\member\model\UsersLevelApplyModel)->getRows();
        $DividendInfo = settings('DividendInfo');
        $UsersModel = new UsersModel();
        Db::startTrans();
        foreach ($userLevel as $level) {
            $where = [];
            $where[] = ['level_id', '>=', $level['level_id']];
            $userIds = $UsersModel->where($where)->column('user_id');
            $prize_pool = bcdiv($total * $DividendInfo['prize_pool'][$level['level_id']], 100,
                    2
                );
            $count = count($userIds);
            foreach ($userIds as $user_id) {
                $userInfo = $UsersModel->info($user_id);
                $dividend_amount = bcdiv($prize_pool, $count, 2);
                if ($dividend_amount > 0) {
                    $res = $this->createLog($userInfo, $dividend_amount, '奖金池分红', $level['level_name'] . '奖金池总金额:' . $prize_pool . '元，分红总人数:' . $count . '，您获得' . $dividend_amount . '元' . $level['level_name'] . '奖金池分红', $prize_pool);
                    if ($res != true) {
                        Db::rollback();
                        die('【分红失败.】');
                    }
                }
            }
        }
        // Db::rollback();
        Db::commit();
        die('【分红完成】');
    }
    /**
     * [createLog 记录分佣日志]
     * @param  [type]  $userInfo         [用户信息]
     * @param  [type]  $dividend_amount  [佣金金额]
     * @param  [type]  $award_name       [分佣名称]
     * @param  [type]  $level_award_name [分佣详情]
     * @param  integer $amount           [总业绩]
     */
    public function createLog($userInfo,float $dividend_amount, string $award_name,$level_award_name,$amount=0)
    {
        $DividendInfo = settings('DividendInfo');
        $dividend_bean = 0;

        $rebate_push_num = (new UsersModel)
                            ->where([
                                ['pid', '=', $userInfo['user_id']],
                                ['role_id', '=', 2],
                                ['profit_pid', '<>', $userInfo['user_id']],
                            ])
                            ->count();


        if ($DividendInfo['rebate_push_num'] > $rebate_push_num) {
            $total_dividend_amount = $dividend_amount;
            $dividend_amount       = 0;
            $dividend_amount       = bcdiv($total_dividend_amount * $DividendInfo['balance_rebate'], 100, 2);
            $dividend_bean         = bcdiv($total_dividend_amount * $DividendInfo['integral_rebate'], 100, 2);
        }

        $inArr['dividend_amount'] = $dividend_amount;
		$inArr['dividend_bean']    = $dividend_bean;
        $inArr['order_type'] = 'bonus';
        $inArr['status'] = 9;
        $inArr['order_id'] = 0;
        $inArr['order_sn'] = 0;
        $inArr['buy_uid'] = 0;
        $inArr['order_amount'] = $amount;
        $inArr['dividend_uid'] = $userInfo['user_id'];
        $inArr['role_id'] = $userInfo['role_id'];
        $inArr['role_name'] = $userInfo['role']['role_name'];
        $inArr['level'] = 0;
        $inArr['award_id'] = 0;
        $inArr['award_name'] = $award_name;
        $inArr['level_award_name'] = $level_award_name;
        $inArr['add_time'] = $inArr['update_time'] = time();
        $res = $this->Model->create($inArr);
        if ($res->log_id < 1) return false;
        $changedata = [];
        $changedata['change_desc'] = $inArr['level_award_name'];
        $changedata['change_type'] = 4;
        $changedata['by_id'] = $inArr['order_id'];
        $changedata['from_uid'] = $inArr['user_id'];
        $changedata['balance_money'] = $inArr['dividend_amount'];
		$changedata['bean_value'] = $inArr['dividend_bean'];
        $changedata['total_dividend'] = $inArr['dividend_amount'] + $inArr['dividend_bean'];
        $res = $this->AccountModel->change($changedata, $inArr['dividend_uid'], false);
        if ($res !== true) {
            return false;
        }
        return true;
    }
}